var core    = require('core')
,   auth    = core.auth
,   tools   = core.tools
,   error   = core.error
,   success = core.success;

module.exports = function(req, res, next){
    var model = require("core").db.model.merchant
    ,   rdata = null;

    model.user.findOne({name : req.body.name || req.query.name}
    , function(err, doc){

        if(err)
            return res.send(error(4));
        else if(doc)
            return res.send(error(25));
        else{
            var name = req.body.name || req.query.name;
            var pwd  = tools.sha1(req.body.pwd || req.query.pwd);

            var user = new model.user({name : name, pwd: pwd});
            user.save(function(err, doc){
                if(err)
                    return res.send(error(4));

                rdata = success();
                rdata.data = [];

                if(eval(req.body.login) || eval(req.query.login))
                    return auth.token(doc.uid, null, function(token){
                        rdata.data = token;
                        res.send(rdata);
                    });

                res.send(rdata);
            });
        }
    });

};